<?php

namespace App\Common;

use Hyperf\Context\Context;

trait Singleton
{
    /**
     * 通过协程上下文获取单例实例
     * 队列等常驻内存类，请走new
     */
    public static function getInstance()
    {
        $param = func_get_args();
        $calledClass = get_called_class();
        $keyArray = $param;
        foreach ($keyArray as $k => $key) {
            $keyArray[$k] = (string)$key;
        }
        $key = empty($keyArray) ? 0 : implode('_', $keyArray);
        $instanceKey = $calledClass . '_' . $key;
        if ($res = Context::get($instanceKey)) {
            return $res;
        }
        $instance = new $calledClass(...$param);
        Context::set($instanceKey, $instance);

        return $instance;
    }
}